#include "manage_page.h"
#include "ui_manage_page.h"
#include "QStandardItemModel"
#include "QPushButton"
#include <QCompleter>
#include <QFile>
#include <QMessageBox>

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>

#include "mainwindow.h"


manage_page::manage_page(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::manage_page)
{
    ui->setupUi(this);
    initUI();

//    QString theme = dynamic_cast<MainWindow*>(parent)->theme;
    QString theme = "gray";
//    QFile login_style("://manage_page.css");
    QFile login_style(":/styles/manage_page_" + theme + ".css");
    login_style.open(QFile::ReadOnly);
    if (!login_style.isOpen()) {
        QMessageBox::warning(this, "","open failed!");
    }
    this->setStyleSheet(login_style.readAll());

    connect(ui->searchBtn, SIGNAL(clicked()), this, SLOT(clickedSearchBtn()));
    connect(ui->saves_btn, SIGNAL(clicked()), this, SLOT(saveAllToDB()));
    connect(ui->delete_btn, SIGNAL(clicked()), this, SLOT(deleteSelectedItem()));

//    test_db();

}

manage_page::~manage_page()
{
    delete ui;
}

void manage_page::initUI()
{
// 禁止修改
//    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);


    QTableView* tableView = ui->tableView;
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView->setSelectionMode(QAbstractItemView::SingleSelection);

    this->tableModel = new QStandardItemModel(this);
    tableView->setModel(tableModel); // recommend to set model before detail settings

    // set columns
    //    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // column fit the contents
    showTextbookTable();

    // 将数据模型绑定到表格中
    ui->tableView->setModel(tableModel);

    // 实现数据改变自动刷新的功能
    QObject::connect(tableModel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), ui->tableView, SLOT(update()));

    QStringList word_list;
    word_list << "岁月史书" << "Play Boy";
    QCompleter* completer = new QCompleter(word_list, this);
    ui->searchEditor->setCompleter(completer);

}

void manage_page::update_table(QVector<QVector<QString>> tabels)
{

}

struct Textbook {
        int textbookID;
        QString author;
        QString date;
        QString bookName;

        QString ISBN;
        double price;
        QString press;
};

void manage_page::showTextbookTable()
{
        QStandardItemModel *tableModel = this->tableModel;
        tableModel->clear();

        QStringList columnTitles;
        columnTitles << "Textbook_ID" << "Author" << "Date" << "BookName" << "ISBN" << "Price" << "Press";
        tableModel->setHorizontalHeaderLabels(columnTitles);
        auto load_json = [=](QNetworkReply* reply){
//            ui->textEdit ->append(QString(reply->readAll()));
            if (reply->error() == QNetworkReply::NoError) {
                // 读取JSON数据
                QByteArray response = reply->readAll();

                // 解析JSON数据
                QJsonDocument jsonDocument = QJsonDocument::fromJson(response);

                if (!jsonDocument.isNull() && jsonDocument.isObject()) {
                    // 处理JSON对象
                    QJsonObject jsonObject = jsonDocument.object();

                    if (jsonObject.contains("textbooks") && jsonObject["textbooks"].isArray()) {
                        // 获取textbooks数组
                        QJsonArray textbooksArray = jsonObject["textbooks"].toArray();

                        // 遍历数组
                        for (const QJsonValue& textbookValue : textbooksArray) {
                            if (textbookValue.isObject()) {
                                // 获取单个教材对象
                                QJsonObject textbookObject = textbookValue.toObject();

                                Textbook textbook;

                                textbook.textbookID = textbookObject["Textbook_ID"].toInt();
                                textbook.author = textbookObject["Author"].toString();
                                textbook.date = textbookObject["Date"].toString();
                                textbook.bookName = textbookObject["BookName"].toString();
                                textbook.ISBN = textbookObject["ISBN"].toString();
                                textbook.price = textbookObject["Price"].toDouble();
                                textbook.press = textbookObject["Press"].toString();

                                // 将解析后的教材信息添加到列表中
//                                textbooks.append(textbook);

                                QList<QStandardItem *> rowItems;
                                rowItems << new QStandardItem(QString::number(textbook.textbookID));
                                rowItems << new QStandardItem(textbook.author);
                                rowItems << new QStandardItem(textbook.date);
                                rowItems << new QStandardItem(textbook.bookName);
                                rowItems << new QStandardItem(textbook.ISBN);
                                rowItems << new QStandardItem(QString::number(textbook.price));
                                rowItems << new QStandardItem(textbook.press);

                                tableModel->appendRow(rowItems);
                            }
                        }
                    }
                }
            } else {
                qDebug() << "Error: " << reply->errorString();
            }

            // 释放资源
            reply->deleteLater();
        };


        QNetworkAccessManager *manager = new QNetworkAccessManager(this);
        connect(manager, &QNetworkAccessManager::finished,
                this, load_json);

        manager->get(QNetworkRequest(QUrl("http://127.0.0.1:5000/getAllTextbooks")));
}

void manage_page::clickedSearchBtn()
{
        showTextbookTable();
}

void manage_page::onTableBtnClicked()
{
    qDebug() << "table push";
}


// 获取QTableView的数据并转换为JSON
QJsonArray manage_page::getJsonDataFromTableView() {
    QStandardItemModel *model = this->tableModel;
    QJsonArray jsonArray;

    for (int row = 0; row < model->rowCount(); ++row) {
        QJsonObject jsonObject;
        for (int column = 0; column < model->columnCount(); ++column) {
            qDebug() << "here";
            QStandardItem *item = model->item(row, column);
            if (item) {
                QStandardItem *headerItem = model->horizontalHeaderItem(column);
                if (headerItem) {
                    qDebug() << "Column Header: " << headerItem->text();
                    qDebug() << "Item Text: " << item->text();
                    if (headerItem->text() == "Price")
                        jsonObject[headerItem->text()] = item->text().toFloat();
                    else if(headerItem->text() == "Textbook_ID")
                        jsonObject[headerItem->text()] = item->text().toInt();
                    else
                        jsonObject[headerItem->text()] = item->text();
                    qDebug() << "here";
                } else {
                    qDebug() << "Horizontal header item is null at column: " << column;
                }
            } else {
                qDebug() << "Item is null at row: " << row << ", column: " << column;
            }
        }
        jsonArray.append(jsonObject);
    }
    qDebug() << "here";
    return jsonArray;
}

void manage_page::saveAllToDB()
{
    qDebug() << "cao";
    QJsonArray jsonData = getJsonDataFromTableView();

//    qDebug() << jsonData;
    sendJsonToServer(jsonData, QUrl("http://127.0.0.1:5000/rewriteAllTextbooks"));
}

bool manage_page::deleteSelectedItem()
{
    QItemSelectionModel *selectionModel = ui->tableView->selectionModel();
    QModelIndexList selectedRows = selectionModel->selectedRows();

    for (int i = selectedRows.size() - 1; i >= 0; --i) {
        tableModel->removeRow(selectedRows.at(i).row());
    }


    return true;

}

bool manage_page::addNewItem(QList<QStandardItem *> rowItems)
{
    tableModel->appendRow(rowItems);
}

// 发送JSON数据到指定地址
void manage_page::sendJsonToServer(const QJsonArray &jsonArray, const QUrl url) {
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply *reply = manager->post(request, QJsonDocument(jsonArray).toJson());
    qDebug() << QJsonDocument(jsonArray).toJson();
    // 处理reply的信号，检查是否成功发送
    connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            // 读取响应数据
            QByteArray responseData = reply->readAll();

            // 处理响应数据
            qDebug() << responseData;
        } else {
            // 处理错误
            qDebug() << "Error: " << reply->errorString();
        }

        // 释放资源
        reply->deleteLater();
    } );
}

// ...
